package com.haidechizi.longpolling.client.adapter;

import com.haidechizi.longpolling.client.entity.LongPollingDto;
import com.haidechizi.longpolling.client.entity.Response;
import com.haidechizi.longpolling.client.service.LongPollingService;
import com.haidechizi.longpolling.constant.CommonConstant;
import com.haidechizi.longpolling.server.entity.ConfigData;
import com.haidechizi.longpolling.server.persistent.ConfigDataPersistent;
import com.haidechizi.longpolling.utils.ResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author wangdejun
 * @create 2021/2/24 11:15
 */
@Component
public class LongPollingAdapter {

    @Autowired
    private LongPollingService longPollingService;

    public void doLongPolling(LongPollingDto longPollingDto, HttpServletRequest request, HttpServletResponse response) {
        // 判断是否支持长轮询
        if (isSupportLongPolling(request)) {
            longPollingService.addLongPollingClient(longPollingDto, request, response);
            return;
        }
        // 兼容短轮训
        ConfigData configData = ConfigDataPersistent.getConfigData(longPollingDto.getAppCode());
        if (configData == null) {
            ResponseUtils.generatorResponse(response, Response.builder().code(-1).message("appCode不存在").build());
            return;
        }
        if (longPollingDto.getMd5().equals(configData.getMd5())) {
            // 数据未发生变化
            ResponseUtils.generatorResponse(response, Response.builder().success());
        }
        ResponseUtils.generatorResponse(response, Response.builder().data(configData));

    }

    private boolean isSupportLongPolling(HttpServletRequest request) {
        return request.getHeader(CommonConstant.LONG_POLLING_TIMEOUT) != null;
    }
}
